package cn.b.sky.mes.andon.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.andon.model.MessageRule;
import cn.b.sky.mes.andon.model.MessageRuleItem;
import cn.b.sky.mes.andon.model.condition.MessageRuleCondition;
import cn.b.sky.mes.andon.service.AndonTypeService;
import cn.b.sky.mes.andon.service.MessageRuleService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

/**
 * 
 * <strong>Title : MessageRuleController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.andon.controller<br></strong>
 * <strong>Description : </strong>消息规则操作控制器<br> 
 * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/messageRule/*")
public class MessageRuleController extends SecurityController {

  @Resource
  MessageRuleService messageRuleService;

  @Resource
  AndonTypeService andonTypeService;

  @Resource
  ECodeService eCodeService;

  /**
   * 
   * <strong>Title : listMessageRulesPageInfo<br></strong>
   * <strong>Description : </strong>根据查询条件查询消息规则分页信息<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param condition 消息规则查询条件
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "listMessageRulesPageInfo")
  public String listMessageRulesPageInfo(String navTabId, @ModelAttribute("condition") MessageRuleCondition condition,
      Model model) {
    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    // 添加SITECODE条件值并查询分页信息
    condition.setSiteCode(siteCode);
    if (StringUtils.isBlank(condition.getOrderField())) {
      condition.setOrderField("CREATEDATETIME");
    }

    model.addAttribute("page", this.messageRuleService.selectMessageRulePageByCondition(condition));
    model.addAttribute("andonTypeList", this.andonTypeService.getAndonAccountListBySiteCode(siteCode, 0));

    return "andon/messageRule/messageRule_list";
  }

  @RequestMapping(value = "lookUpMessageRulesPageInfo")
  public String lookUpMessageRulesPageInfo(String navTabId, @ModelAttribute("condition") MessageRuleCondition condition,
      Model model) {
    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    // 添加SITECODE条件值并查询分页信息
    condition.setSiteCode(siteCode);
    if (StringUtils.isBlank(condition.getOrderField())) {
      condition.setOrderField("CREATEDATETIME");
    }

    model.addAttribute("page", this.messageRuleService.selectMessageRulePageByCondition(condition));
    model.addAttribute("andonTypeList", this.andonTypeService.getAndonAccountListBySiteCode(siteCode, 0));

    return "andon/messageRule/messageRule_lookup";
  }

  /**
   * 
   * <strong>Title : viewMessageRule<br></strong>
   * <strong>Description : </strong>根据主键查询消息规则对象<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param siteCode 工厂编号
   * @param ruleCode 消息规则编号
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "viewMessageRule")
  public String viewMessageRule(String navTabId, String ruleCode, Model model) {
    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    
    MessageRule messageRule = this.messageRuleService.getMessageRulesWithAssociatedData(siteCode, ruleCode);

    if (null != messageRule && !CollectionUtils.isEmpty(messageRule.getMessageRuleItemList())) {
      Map<String, ECode> monitorMap = this.eCodeService.selectECodeMap(ECodeEnums.ANDONMESSAGE_MONITOR_STATUS.getCode(),
          this.getCurrentLanguage());
      Map<String, ECode> timeStartTypeMap = this.eCodeService
          .selectECodeMap(ECodeEnums.ANDONMESSAGE_TIMER_START_TYPE.getCode(), this.getCurrentLanguage());

      ECode monitorECode = null, timeStartTypeECode = null;
      for (MessageRuleItem messageRuleItem : messageRule.getMessageRuleItemList()) {
        monitorECode = monitorMap.get(messageRuleItem.getStatusEcode());
        if (null != monitorECode) {
          messageRuleItem.setStatusEcodeText(monitorECode.geteCodeText());
        }

        timeStartTypeECode = timeStartTypeMap.get(messageRuleItem.getTimerStartEcode());
        if (null != timeStartTypeECode) {
          messageRuleItem.setTimerStartEcodeText(timeStartTypeECode.geteCodeText());
        }
      }

    }
    
    model.addAttribute("messageRule", messageRule);
    
    model.addAttribute("andonTypeList", this.andonTypeService.getAndonAccountListBySiteCode(siteCode, 0));
    return "andon/messageRule/messageRule_view";
  }

  /**
   * 
   * <strong>Title : toAddMessageRule<br></strong>
   * <strong>Description : </strong>新增消息规则信息前置事件<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toAddMessageRule")
  public String toAddMessageRule(String navTabId, Model model) {

    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("andonTypeList", this.andonTypeService.getAndonAccountListBySiteCode(this.getSiteCode(), 0));

    return "andon/messageRule/messageRule_edit";
  }

  /**
   * 
   * <strong>Title : toEditMessageRule<br></strong>
   * <strong>Description : </strong>修改消息规则信息前置事件<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param siteCode 工厂编号
   * @param ruleCode 消息规则编号
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toEditMessageRule")
  public String toEditMessageRule(String navTabId, String ruleCode, Model model) {

    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    MessageRule messageRule = this.messageRuleService.getMessageRulesWithAssociatedData(siteCode, ruleCode);

    if (null != messageRule && !CollectionUtils.isEmpty(messageRule.getMessageRuleItemList())) {
      Map<String, ECode> monitorMap = this.eCodeService.selectECodeMap(ECodeEnums.ANDONMESSAGE_MONITOR_STATUS.getCode(),
          this.getCurrentLanguage());
      Map<String, ECode> timeStartTypeMap = this.eCodeService
          .selectECodeMap(ECodeEnums.ANDONMESSAGE_TIMER_START_TYPE.getCode(), this.getCurrentLanguage());

      ECode monitorECode = null, timeStartTypeECode = null;
      for (MessageRuleItem messageRuleItem : messageRule.getMessageRuleItemList()) {
        monitorECode = monitorMap.get(messageRuleItem.getStatusEcode());
        if (null != monitorECode) {
          messageRuleItem.setStatusEcodeText(monitorECode.geteCodeText());
        }

        timeStartTypeECode = timeStartTypeMap.get(messageRuleItem.getTimerStartEcode());
        if (null != timeStartTypeECode) {
          messageRuleItem.setTimerStartEcodeText(timeStartTypeECode.geteCodeText());
        }
      }

    }

    model.addAttribute("messageRule", messageRule);

    model.addAttribute("andonTypeList", this.andonTypeService.getAndonAccountListBySiteCode(siteCode, 0));

    return "andon/messageRule/messageRule_edit";
  }

  /**
   * 
   * <strong>Title : saveMessageRule<br></strong>
   * <strong>Description : </strong>新增或修改消息规则信息<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param messageRule 消息规则
   * @param model 页面值对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "saveMessageRule")
  @ResponseBody
  public DWZResult saveMessageRule(String navTabId, MessageRule messageRule, Model model) {
    if (null == messageRule) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }

    messageRule.setSiteCode(getSiteCode());
    setCreateInfo(messageRule);

    if (null == messageRule.getLockFlag()) {
      messageRule.setLockFlag(0);
    }
    
    if (null == messageRule.getAllAndonsFlag()) {
      messageRule.setAllAndonsFlag(0);
    }
    
    
    if (!this.messageRuleService.existMessageRuleByPrimaryKey(messageRule.getSiteCode(), messageRule.getRuleCode())) {
      this.messageRuleService.insertMessageRulesWithAssociatedData(messageRule);
    } else {
      this.messageRuleService.updateMessageRulesWithAssociatedData(messageRule);
    }

    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }

  /**
   * 
   * <strong>Title : deleteMessageRuleBatch<br></strong>
   * <strong>Description : </strong>删除消息规则信息<br> 
   * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param model 页面值对象
   * @param request 页面请求对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "deleteMessageRuleBatch")
  @ResponseBody
  public DWZResult deleteMessageRuleBatch(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String siteCode = this.getSiteCode();
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    BatchJobReport report = null;
    for (String res : ress) {

      try {
        report = this.messageRuleService.deleteMessageRulesWithAssociatedData(siteCode, res);
      } catch (Exception e) {
        report = new BatchJobReport(res, e.getMessage(), false);
      }

      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }

    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  /**
   * 
   * <strong>Title : toAddMessageRuleItem<br></strong>
   * <strong>Description : </strong>TODO@方法注释说明写在此处@<br> 
   * <strong>Create on : 2016年10月18日 上午9:26:28<br></strong>
   * <p>
   * @param navTabId 页面TAB的ID
   * @param model 数据模型
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toAddMessageRuleItem")
  public String toAddMessageRuleItem(String navTabId, Model model) {

    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("timerStartTypeList", eCodeService
        .selectECodeList(ECodeEnums.ANDONMESSAGE_TIMER_START_TYPE.getCode(), SecurityContextUtil.getLanguageCode()));
    model.addAttribute("monitorStatusList", eCodeService
        .selectECodeList(ECodeEnums.ANDONMESSAGE_MONITOR_STATUS.getCode(), SecurityContextUtil.getLanguageCode()));
    model.addAttribute("timeUnitList", eCodeService.selectECodeList(ECodeEnums.ANDONMESSAGE_TIMEUNIT.getCode(),
        SecurityContextUtil.getLanguageCode()));

    return "andon/messageRule/messageRuleItem_add";
  }

  
  /**
   * 
   * <strong>Title : validateMessageRuleCodeExist<br></strong>
   * <strong>Description : </strong>验证消息规则配置编码是否存在<br> 
   * <strong>Create on : 2016年10月26日 上午10:11:33<br></strong>
   * <p>
   * @param messageRuleCode 消息规则配置编码
   * @param model 数据模型
   * @return
   * boolean 是否存在
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("validateMessageRuleCodeExist")
  @ResponseBody
  public boolean validateMessageRuleCodeExist(String ruleCode, Model model) {
    if (!StringUtils.isEmpty(ruleCode)) {
      return !this.messageRuleService.existMessageRuleByPrimaryKey(this.getSiteCode(), ruleCode.toUpperCase());
    }
    return false;
  }
}
